<script setup>
import { appStockListQuery } from "@/services/cashier";
import { onLoad, onReady, onShow, onReachBottom } from "@dcloudio/uni-app";
import { nextTick, ref, watch, onMounted } from "vue";
import { appOrderQuery } from "@/services/cashier";
import { isOpens } from "@/utils/directive.js";

const form = ref({
  pageIndex: 1,
  pageSize: 20,
  code: "",
  createStartTime: "",
  createEndTime: "",
  shopId: "",
  status: "",
  sortField: "createTime",
  sortOrder: "DESC",
});

const topHeight = ref(uni.getStorageSync("topHight") || 0);
const userObj = ref({});
const showSelect = ref("");
const ids = ref("");
const shopName = ref("");

onReachBottom(() => {
  console.log("触底了");
  getAppProductQuery();
});

onLoad((options) => {
  ids.value = options.ids ? options.ids : "";
  shopName.value = options.shopName ? options.shopName : "";
  if (uni.getStorageSync("user")) {
    userObj.value = JSON.parse(uni.getStorageSync("user"));
  }

  if (uni.getStorageSync("selectShopType")) {
    showSelect.value = uni.getStorageSync("selectShopType");
  }

  // options1.value = [userObj.value];
  // getAppShopSelector();
});
onShow(() => {
  getAppProductQuery(1);
});
onReady(() => {
  // 微信小程序需要用此写法
  // datetimePickerRef.value.setFormatter(formatter);
});
const selectShow = ref(false);
function open() {
  // 打开逻辑，比如设置 show 为 true
  // selectShow.value = true;
  // console.log('open');
}

const productData = ref([]);

const loading = ref("");
const getAppProductQuery = async (index) => {
  console.log("form", userObj.value.shopId, userObj.value);
  console.log("index", index);
  if (index == 1) {
    productData.value = [];
    loading.value = "";
  }
  if (index) {
    form.value.pageIndex = index;
  }
  if (loading.value == "noMore") {
    return;
  }
  loading.value = "Loading";

  if (showSelect.value == "admin") {
  } else {
    form.value.shopIds = [];
    form.value.shopId = userObj.value.shopId;
  }
  if (ids.value) {
    form.value.shopIds = [ids.value];
  }
  if (ids.value) {
    form.value.shopIds = [ids.value];
  }
  try {
    let res = await appOrderQuery({
      shopId: userObj.value.shopId,
      ...form.value,
    });
    if (res.code == 200) {
      console.log(res);

      console.log(productData.value);
      form.value.pageIndex = form.value.pageIndex + 1;

      if (res.data.datas.length < form.value.pageSize) {
        loading.value = "noMore";
      } else {
        loading.value = "More";
      }
      let arr = [];

      res.data.datas.forEach((item) => {
        if (arr.length > 0) {
          if (arr[arr.length - 1].time == item.createTime.substring(0, 10)) {
            arr[arr.length - 1].list.push(item);
          } else {
            arr.push({
              time: item.createTime.substring(0, 10),
              list: [item],
            });
          }
        } else {
          arr.push({
            time: item.createTime.substring(0, 10),
            list: [item],
          });
        }
      });
      productData.value = productData.value.concat(arr);
      console.log(arr);
    } else {
    }

    console.log(res);
  } catch (e) {}
};

const searchFun = () => {
  console.log("searchFun");
  uni.navigateTo({
    url: `/pages/cashier/sales_search/index?ids=${
      ids.value
    }&shopName=${decodeURIComponent(shopName.value)}`,
  });
};
const goDet = (item) => {
  if (showSelect.value == "shop") {
    if (!isOpens(["shop:order:detail"])) return;
  }
  if (showSelect.value == "admin") {
    if (!isOpens(["manager:order:detail"])) return;
  }

  uni.navigateTo({
    url: "/pages/cashier/sales_order_det/index?id=" + item.id,
  });
};
const list1 = ref([
  { name: "全部", value: "" },
  { name: "已支付", value: 3 },
  { name: "未支付", value: 0 },
]);
const tabsClick = (item) => {
  form.value.status = item.value;
  getAppProductQuery(1);
};
const copyFun = (ids) => {
  uni.setClipboardData({
    data: ids,
    success: function () {
      uni.showToast({
        title: "复制成功",
        icon: "none",
      });
    },
  });
};

const canRefund = (item) => {
  uni.navigateTo({
    url: "/pages/cashier/refund/index?id=" + item.id,
  });
};

//无网状态
const connected = () => {
  getAppProductQuery();
};
</script>

<template>
  <view class="bg">
    <top-nav
      :title="'销售单查询'"
      :border="false"
      @search="searchFun"
      rType="iconSearch"
    ></top-nav>

    <view class="shop-name" :style="'top: calc( 88rpx + ' + topHeight + 'px);'">
      <up-tabs
        :list="list1"
        lineWidth="30"
        lineColor="#169bf1"
        @click="tabsClick"
        :activeStyle="{
          color: '#169bf1',
          fontWeight: 'bold',
          transform: 'scale(1.05)',
        }"
        :inactiveStyle="{
          color: '#606266',
          transform: 'scale(1)',
        }"
        itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;font-size: 28rpx;"
      >
      </up-tabs>
      <view class="shop-name_title" v-if="shopName">{{ shopName }}</view>
    </view>

    <view class="content">
      <view
        class="content-item"
        v-for="(item, index) in productData"
        :key="index"
      >
        <view class="content-item-title">{{ item.time }}</view>
        <view class="content-list">
          <view
            class="content-list-item"
            @click="goDet(order)"
            v-for="(order, orIndex) in item.list"
            :key="orIndex"
          >
            <view class="content-list-item-title"
              ><text>{{ order.productName }} </text>
              <!-- v-if="refundStatus == 1" -->
              <view
                class="status-text"
                :class="order.status == 3 ? 'status-text1' : 'status-text2'"
                >{{ order.status == 3 ? "已支付" : "未支付" }}</view
              >
              <!-- <view
                v-else
                class="status-text"
                style="color: ;"
                >{{ order.status == 3 ? "已支付" : "未支付" }}</view
              > -->
            </view>

            <view class="content-list-item-flex">
              <view class="flex-1 flex"
                >订单编号
                <text @click.stop="copyFun(order.code)"> {{ order.code }}</text
                ><text @click.stop="copyFun(order.code)" class="copy"></text>
              </view>
            </view>
            <view class="content-list-item-flex">
              <view class="flex-2"
                >合计金额 <text>¥{{ order.totalAmount }}</text>
              </view>

              <view class="flex-2"
                >合计数量 <text>{{ order.totalNum }}</text>
              </view>
            </view>

            <view class="content-list-item-flex">
              <!-- <view class="flex-1"
                >下单时间 <text>{{ order.createTime }}</text>
              </view> -->
              <view class="flex-2"
                >下单时间 <text>{{ order.createTime }}</text>
              </view>

              <view style="color: #ff6a00" class="flex-2" v-if="order.refundFee"
                >退款金额
                <text
                  ><text>¥{{ order.refundFee }}</text>
                </text>
              </view>
            </view>
            <view
              v-permission="['manager:pay:refund', 'shop:pay:refund']"
              class="pay_TK"
              v-if="order.canRefund"
              ><button class="button-hover" @click.stop="canRefund(order)">
                退货退款
              </button></view
            >
          </view>
        </view>
      </view>
    </view>
    <view class="noData" v-if="productData.length <= 0 && loading == 'noMore'">
      <view class="noData-img">
        <image src="@/static/nodate/datas.png" mode="scaleToFill" />
        <view>暂无商品 </view>
      </view>
    </view>
    <view class="loading-form" v-if="loading && productData.length > 0"
      ><van-loading size="24rpx" v-if="loading == 'Loading'"
        ><text class="loading-text">加载中...</text>
      </van-loading>
      <text class="loading-text" v-if="loading == 'More'">加载更多</text>
      <text class="loading-text" v-if="loading == 'noMore'">~没有数据了~</text>
    </view>
  </view>
  <up-datetime-picker
    class="top-center"
    :hasInput="false"
    @close="showtime = false"
    @confirm="confirmDate"
    @cancel="showtime = false"
    format="YYYY-MM-DD"
    :show="showtime"
    v-model="timevalue"
    :closeOnClickOverlay="true"
    mode="date"
  >
  </up-datetime-picker>

  <up-popup
    :closeable="true"
    :show="selectShow"
    @close="selectShow = false"
    :safeAreaInsetBottom="true"
    @open="open"
    round="15"
  >
    <view class="popup-content">
      <view class="popup-content-title" @click="showtime = false"></view>
      <view class="popup-content-selTop">快捷选择</view>
      <view class="kj-select">
        <view class="kj-select-item kj-select-item-seleect"> 今日 </view>
        <view class="kj-select-item"> 昨日 </view>
        <view class="kj-select-item"> 近7日 </view>
        <view class="kj-select-item"> 本周 </view>
        <view class="kj-select-item"> 本月 </view>
        <view class="kj-select-item"> 上周 </view>
        <view class="kj-select-item"> 上月 </view>
      </view>
      <view class="popup-content-selTop">自定义</view>
      <view class="kj-select">
        <view class="kj-select-item"> 今日 </view>
        <view class="kj-select-item"> 昨日 </view>
        <view class="kj-select-item"> 近7日 </view>
      </view>
      <view class="bt-text"> 报表统计时间:0:00-次日0:00 </view>
    </view>
  </up-popup>
  <noWork @connected="connected"> </noWork>
</template>

<style lang="scss" scoped>
@import "index.scss";
</style>
